import config
import obj_config
import apps
import language
import settings


class Calls_funcs:
    def shell_scheduler(self, id_func, func_name, call_shell, tags=[]):
        # Оболочка вызова
        # Например в цикле
        if call_shell == "searhc":
            # print("\n\n\n\n\n\n\n\n\n",config.speech_recognition_str_api)
            search = obj_config.service_functions_obj.del_func_str(
                func_name, config.speech_recognition_str_api
            )
            self.A(id_func, func_name, search)

        elif call_shell == "local_net_cmd":
            self.A(id_func, func_name, search)
        else:
            pass

    def call_function(self, func: str, tags: list = []):
        if self.consent_for_activation(func):
            if config.cmds_void[func]["function_classification"] == "egg":
                self.function_call_processing(func, obj_config.obj_import_egg, tags)
            elif config.cmds_void[func]["function_classification"] == "core_utilities":
                if config.cmds_void[func]["class_name"] == "Apps":
                    obj_config.obj_import_core_app.class_name(apps.Apps())
                elif config.cmds_void[func]["class_name"] == "Settings_Kernel":
                    obj_config.obj_import_core_app.class_name(
                        settings.Settings_Kernel()
                    )
                self.function_call_processing(
                    func, obj_config.obj_import_core_app, tags
                )
            elif config.cmds_void[func]["function_classification"] == "collection":
                self.wrapper_collection_functions(func)

    def A(self, id_func, func, tags=[]):
        # try:
        if config.cmds["void"][func]["config_void_func"] == "no_import":
            if tags:
                # print(tags," dnfklhzdlknkjn;jd fdfh")
                mess = id_func(tags)
                obj_config.communication_obj.message_typle(mess)
            else:
                mess = id_func()
                obj_config.communication_obj.message_typle(mess)
        elif config.cmds["void"][func]["config_void_func"] == "import":
            if tags:
                # print({func:config.cmds["void"][func]})
                mess = id_func(tags, {func: config.cmds["void"][func]})
                obj_config.communication_obj.message_typle(mess)
            else:
                mess = id_func(func, {func: config.cmds["void"][func]})
                obj_config.communication_obj.message_typle(mess)
        # except:
        # obj_config.communication_obj.message("Ошибка вызова функции")

    def function_call_processing(self, func: str, class_import_obj, tags: list = []):
        # tags:list=[] ?
        class_import_obj.keys(func)
        id_func = class_import_obj.import_func()
        if config.cmds_void[func]["call shell"] == "standard":
            if "const" in config.cmds_void[func]["tags"]:
                tags = config.cmds_void[func]["tags"]["const"]["tags_list"]
                self.A(id_func, func, tags)
            elif "None" in config.cmds_void[func]["tags"]:
                self.A(id_func, func)
            else:
                # print("жопа 22222")
                self.A(id_func, func, tags)
        elif config.cmds_void[func]["call shell"] != "standard":
            self.shell_scheduler(id_func, func, config.cmds_void[func]["call shell"])

    def label_approval(self, func: str) -> bool:
        """Проверка вызываемой команды является вызванная функция с параметрами

        Если True, то функция не имеет параметров.
        Если False, то имеет параметры.

        """
        return ("None" in config.cmds_void[func]["tags"]) or (
            "const" in config.cmds_void[func]["tags"]
        )

    def consent_for_activation(self, ch_func):
        """
        Данная функция спращивает разрещение на активацию вызываемой функции.

        Параметры:
        `ch_func`: Имя функции

        **enabling_activation** глобальный параметр разрещения на запрос об активации.
        Также в каждой функции есть локальный парметр разрещения на активацию
        Исправить: Локальный парметр в случае запрета не спрашвиает разрешение на активацию

        Возращает:
        **Булевый тип**
        True в случае разращения на активацию
        False в случае запрета на активацию

        """
        if config.enabling_activation:
            if config.cmds_void[ch_func]["speech test"]:
                yes = config.cmds["other"]["yes"]
                no = config.cmds["other"]["no"]
                obj_config.communication_obj.messege(
                    language["call_funcs=>Calls_funcs"][
                        "util_consent_for_activation_CALL_FUNC"
                    ]
                )
                consent = obj_config.obj_api.queue_voice_time_str_api()
                if consent in yes:
                    obj_config.communication_obj.messege(
                        language["call_funcs=>Calls_funcs"][
                            "util_consent_for_activation_CMD_TRUE"
                        ]
                    )
                    return True
                elif consent in no:
                    obj_config.communication_obj.messege(
                        language["call_funcs=>Calls_funcs"][
                            "util_consent_for_activation_CMD_FALSE"
                        ]
                    )
                    return False
                else:
                    obj_config.communication_obj.messege(
                        language["call_funcs=>Calls_funcs"][
                            "util_consent_for_activation_CMD_REC"
                        ]
                    )
                    return False
        else:
            return True

    def wrapper_collection_functions(self, name_collection):
        # Оболочка коллекций collection_functions
        if not config.hidden_function:
            if name_collection in config.cmds["collection"]:
                funcs = config.cmds["collection"][name_collection]
                # Может быть рекурсия, ОПАСНО !!!
                self.collection_functions(funcs)
            else:
                obj_config.communication_obj.messege(
                    language["call_funcs=>Calls_funcs"][
                        "wrapper_collection_functions_COLLECT"
                    ]
                )
        elif config.hidden_function:
            if name_collection in config.cmds["collection"]:
                funcs = config.cmds["collection"][name_collection]
                obj_config.communication_obj.message_stop_or_play()
                self.collection_hidden_function_execution_no_m(funcs)
                obj_config.communication_obj.message_stop_or_play()

            else:
                pass
        else:
            pass

    def collection_functions(self, funcs):
        for func in funcs:
            if "tags" in config.cmds_void[func]["tags"]:
                temp = language["call_funcs=>Calls_funcs"][
                    "collection_functions_SPEECH_TAGS_FUNC"
                ]
                obj_config.communication_obj.messege(temp)
                if config.tags_decoder_flag:
                    tags = obj_config.tags_wrapper_obj.selection_tags()
                    self.call_function(func, tags)
                elif not config.tags_decoder_flag:
                    tags = obj_config.tags_wrapper_obj.selection_tags(
                        obj_config.obj_api.queue_voice_time_str_api()
                    )
                    self.call_function(func, tags)
            elif "const" in config.cmds_void[func]["tags"]:
                tags = config.cmds_void[func]["tags"]["const"]["tags_list"]
                self.call_function(func, tags)
            elif "None" in config.cmds_void[func]["tags"]:
                self.call_function(func)
            elif "key" in config.cmds_void[func]["tags"]:
                # !!!!!!!!!!!!!!!!!!
                self.call_function(func, tags)

    def collection_hidden_function_execution_no_m(self, funcs):
        for func in funcs:
            if "const" in config.cmds_void[func]["tags"]:
                tags = config.cmds_void[func]["tags"]["const"]["tags_list"]
                self.call_function(func, tags)
            elif "None" in config.cmds_void[func]["tags"]:
                self.call_function(func)
        obj_config.communication_obj.messege(
            language["call_funcs=>Calls_funcs"][
                "collection_hidden_function_execution_no_m"
            ]
        )


class Wrapper_calls_func:
    def Main_call_func(self):
        # Функция вызова помощника по имени
        # Проверка на имя помощника
        obj_config.obj_work_mode.wrapper_timer(
            config.work_mode, obj_config.obj_work_mode.cheek_timer_name
        )
        cmd_say = obj_config.wrapper_decoders_obj.dec_activation_name()
        # print(cmd_say,2222222)
        # Если вызвали его
        # if len(name_or_func) != 0 and
        # obj_config.obj_work_mode.cheek_sleep(name_or_func)==True:
        if cmd_say:
            # ТО ищем функции
            obj_config.obj_work_mode.update_timer_name()
            # print(cmd_say, 111111)
            funcs = obj_config.wrapper_decoders_obj.dec_activation_fuck(cmd_say)
            self.calls_cmd_no_spech_recogn(funcs, cmd_say)

    def calls_cmd_no_spech_recogn(self, funcs: list, cmd_say="") -> None:
        for func in funcs:
            cheek_say_value = obj_config.service_functions_obj.cheek_say(
                config.cmds_void[func]["word_list"][0]
            )
            if cheek_say_value:
                print(func)
                label = obj_config.calls_funcs_obj.label_approval(func)
                print(label)
                if label:
                    # obj_config.obj_work_mode.update_timer_name()
                    obj_config.calls_funcs_obj.call_function(func)
                elif not label:
                    tags = ""
                    tags_v2 = obj_config.obj_tags_v2.cheek_tags_v2(func, cmd_say)
                    if tags_v2 == "tags":
                        tags = obj_config.obj_tags_wraper.selection_tags(tags, func)
                        if obj_config.obj_tags_wraper.check_tags(func, tags) and tags:
                            # print(value_tags,"[vzxm omadfkpv'm pdv0000000000001111")
                            obj_config.calls_funcs_obj.call_function(func, tags)
                        else:
                            obj_config.communication_obj.message(
                                language.language["call_funcs=>Wrapper_calls_func"][
                                    "calls_FALSE_TAGS"
                                ]
                            )
                    elif tags_v2 == "key":
                        value_tags = obj_config.obj_tags_v2.dict_word_searhc(
                            cmd_say, func
                        )
                        # print(value_tags,"[vzxm omadfkpv'm pdv00000000000022222")
                        if (
                            value_tags
                            and value_tags["key_value"]
                            and value_tags["values"]
                        ):
                            obj_config.calls_funcs_obj.call_function(func, value_tags)
                        else:
                            obj_config.communication_obj.message(
                                "Список ключевых слов пуст"
                            )
                        # else:
                        # obj_config.communication_obj.messege(language["call_funcs=>Wrapper_calls_func"]["calls_FALSE_TAGS"])
                    else:
                        pass
                else:
                    obj_config.communication_obj.message(
                        language.language["call_funcs=>Wrapper_calls_func"][
                            "calls_cmd_no_spech_recogn"
                        ]
                    )
            else:
                obj_config.communication_obj.message(
                    language.language["call_funcs=>Wrapper_calls_func"][
                        "calls_NOT_UNDERSTAND"
                    ]
                )
